<?php

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\helper\Time;
use mes\Mes;

/**
 * 定时同步图片
 * @author King
 *
 */
class CronDownloadPic extends Command
{

    protected $logName = 'cronDownloadPic';

    protected function configure()
    {
        $this->setName('cronDownloadPic')
            ->addOption('type', 't', Option::VALUE_OPTIONAL, '分类', '')
            ->setDescription('定时同步图片');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '5120M');
        error_reporting(E_ALL & ~E_NOTICE);
        $type = $input->getOption('type');
        switch ($type) {
            case 'temp':
                return $this->sam_download();
                break;
            case 'local':
                return $this->checkpic();
                break;
        }

        try {
//            $where = [
//                ['pic', 'like', ['https://lt-plm.oss-cn-shenzhen.aliyuncs.com%', 'http://file.ltwebstatic.com%', 'https://lt-plm.oss-cn-shenzhen.aliyuncs.com'], 'OR'],
//            ];
            $where = [
                ['pic', 'not like', ['http://www.020mimo.com%', 'https://www.020mimo.com%']],
            ];
            $skuIds = db('sku')->where($where)->column('id');

            foreach ($skuIds as $k => $v) {
                queue('app\common\job\DownloadPic', $v, rand(0, 10), 'DownloadPic');
            }
            $this->_consoleLog('ID ' . implode(',', $skuIds) . '已入队列', 'downloadPic');
        } catch (\Exception $e) {
            $msg = "错误:" . $e->getMessage();
            $this->_consoleLog($msg, 'Exception');
            $output->write(json_encode(['code' => 0, 'msg' => $msg, 'data' => ['start' => $startTime, 'end' => $endTime, 'time' => $time, 'force' => $forceUpdate, 'print' => $this->isPrint, 'totalOrders' => $totalOrders, 'syncOrders' => $syncOrders, 'waitOrders' => $waitOrders]]));
        }
    }


    /**
     * 记录日志并打印
     *
     * @param string $msg
     * @param string $flag
     * @param string $format
     * @author KING
     * @date 2020年6月11日
     *
     */
    private function _consoleLog($msg, $flag, $format = true)
    {
        consoleLog($msg, $flag, $format);
        addLog($msg, $this->logName . $this->mes);
    }

    private function sam_download()
    {
        //1,查找要及时下载的图片
        $sql = "select o.id ,o.client_ordernum ,s.sku,s.pic,s.ori_pic ,s.pic_download_flag
,oext.pic as oext_pic ,oext.ori_pic as ext_ori_pic
from wx_order o
LEFT JOIN wx_order_ext oext on(oext.order_id =o.id)
LEFT JOIN wx_sku s on(s.sku =o.sku)
where 1=1 
and s.pic_download_flag < 10
and
(
(oext.ori_pic <> ''
and oext.ori_pic <>'https://doc.020mes.com/doc_020mes/2022/03/04/16463651693636538893.png'
)
 or
 s.pic_download_flag=1
)
GROUP BY s.sku
";
        //2,下载图片，并标识下载方法与更新下载地址  order_ext sku  2个表的数据
        $list = db()->query($sql);
        //3,去除已经下载的图片
        $down_0 = $this->down_0();
        $list_res = [];

        foreach ($list as $k => $v) {
            $flag = 0;
            foreach ($down_0 as $k2 => $v2) {
                if ($v2['sku'] == $v['sku']) {
                    $flag = 1;
                }
            }
            $flag == 0 && $list_res[] = $v;
        }

        $down_num = 0;
        foreach ($list_res as $k => $v) {
            $pic = downloadPic($v['ori_pic'], $error);
            if ($pic != '') {
                $this->pic_download_add($v,$pic);
                db('sku')->where('sku', $v['sku'])->update(['pic' => $pic, 'pic_download_flag' => 10]);
                db('order_ext')->where('order_id', $v['id'])->update(['pic_download' => $pic]);
                $this->del_pic($v);
                $down_num++;
            } else {
                db('sku')->where('sku', $v['sku'])->update(['pic' => $pic, 'pic_download_flag' => 20]);
            }
        }
        echo $down_num . "--Done" . PHP_EOL;
        return false;
    }

    private function del_pic($skuInfo)
    {
        $msg = '';
        if ($skuInfo['pic'] != '') {
            // 删除旧图片（http://www.020mimo.com/upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg）
            $oldPicPath = parse_url($skuInfo['pic'], PHP_URL_PATH); // /upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg
            $oldPic = env('root_path') . 'public' . $oldPicPath;
            if (file_exists($oldPic)) {

                if (unlink($oldPic)) $msg = $msg . "，成功删除旧图片：" . $oldPicPath;
                else $msg = $msg . "，删除旧图片失败：" . $oldPicPath;
            } else $msg = "，旧图片不存在：" . $oldPicPath;
        } else $msg = "，无旧图片";
    }

    //本地下载的图片，上传到线上，地址也上传

    /**
     * 本地下载的图片，上传到线上，地址也上传
     * 1,使用sam_download  方法下载图片。但不用下载已经下载过的。
     * 2，
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/20
     */
    public function local_to_line()
    {
//1,本地已下载的图片
        $sql = "select o.id ,o.client_ordernum ,s.sku,s.pic,s.ori_pic ,s.pic_download_flag
,oext.pic as oext_pic ,oext.ori_pic as ext_ori_pic
from wx_order o
LEFT JOIN wx_order_ext oext on(oext.order_id =o.id)
LEFT JOIN wx_sku s on(s.sku =o.sku)
where 1=1 
and

 s.pic_download_flag=10

GROUP BY s.sku
";
        $list = db()->query($sql);
        foreach ($list as $k => $v) {
            if ($v['pic'] != '') {
                // 删除旧图片（http://www.020mimo.com/upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg）
                $oldPicPath = parse_url($v['pic'], PHP_URL_PATH); // /upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg
                $oldPic = env('root_path') . 'public' . $oldPicPath;
                if (file_exists($oldPic)) {
                    $info = db('pic_download')->where(['sku' => $v['sku']])->find();
                    if (!isset($info['id'])) {
                        db('pic_download')->insert([
                            'order_id' => $v['order_id'] ?? 0,
                            'client_ordernum' => $v['client_ordernum'] ?? '',
                            'sku' => $v['sku'],
                            'souce_url' => $v['ori_pic'],
                            'download_url' => $v['pic'],
                            'download_all' => $v['pic'],
                            'upload_flag' => 0,
                            'save_flag' => 1,
                        ]);
                    } else {
                        db('pic_download')
                            ->where(['sku' => $v['sku']])
                            ->update([
                                'download_all' => "{$info['download_all']};{$v['pic']}",
                            ]);
                    }

                }
            }

        }
//        //线上访问
//        Db::connect([
//            // 数据库类型
//            'type' => 'mysql',
//            // 数据库连接DSN配置
//            'dsn' => '',
//            // 服务器地址
//            'hostname' => '127.0.0.1',
//            // 数据库名
//            'database' => 'thinkphp',
//            // 数据库用户名
//            'username' => 'root',
//            // 数据库密码
//            'password' => '',
//            // 数据库连接端口
//            'hostport' => '',
//            // 数据库连接参数
//            'params' => [],
//            // 数据库编码默认采用utf8
//            'charset' => 'utf8',
//            // 数据库表前缀
//            'prefix' => 'think_',
//        ])->table('user')->find();
    }

    public function down_0()
    {
        $sql = "select * from wx_pic_download pd ";
        $list = db()->query($sql);
        return $list;
    }

    public function pic_download_add($v,$down_pic){
        $v['pic']=$down_pic;
        if ($v['pic'] != '') {
            // 删除旧图片（http://www.020mimo.com/upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg）
            $oldPicPath = parse_url($v['pic'], PHP_URL_PATH); // /upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg
            $oldPic = env('root_path') . 'public' . $oldPicPath;
            if (file_exists($oldPic)) {
                $info = db('pic_download')->where(['sku' => $v['sku']])->find();
                if (!isset($info['id'])) {
                    db('pic_download')->insert([
                        'order_id' => $v['order_id'] ?? 0,
                        'client_ordernum' => $v['client_ordernum'] ?? '',
                        'sku' => $v['sku'],
                        'souce_url' => $v['ori_pic'],
                        'download_url' => $v['pic'],
                        'download_all' => $v['pic'],
                        'upload_flag' => 0,
                        'save_flag' => 1,
                    ]);
                } else {
                    db('pic_download')
                        ->where(['sku' => $v['sku']])
                        ->update([
                            'download_all' => "{$info['download_all']};{$v['pic']}",
                        ]);
                }

            }
        }
    }

    public function checkpic(){
        $sql = "select * from wx_pic_download pd ";
        $list = db()->query($sql);
        foreach ($list as $k=>$v){
            $oldPicPath = parse_url($v['download_url'], PHP_URL_PATH); // /upload/202112/21/f5125cb6496bec04ac0b28e437eacf48.jpg
            $oldPic = env('root_path') . 'public' . $oldPicPath;
            if (file_exists($oldPic)) {
                db('pic_download')
                    ->where(['sku' => $v['sku']])
                    ->update([
                        'save_flag' => 1,
                    ]);
            }else{
                db('pic_download')
                    ->where(['sku' => $v['sku']])
                    ->update([
                        'save_flag' => 0,
                    ]);
            }
        }
    }
}